package com.wuyangnju.lj.simulation.slave;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wuyangnju.lj.simulation.common.CommonStrings;

public class SlaveArgsParser {
	private static final Log log = LogFactory.getLog(SlaveArgsParser.class);

	public static SlaveCnf parse(String[] args) {
		SlaveCnf cnf = new SlaveCnf();

		Options options = new Options();
		options.addOption("h", "help", false, "help");
		options.addOption("s", "server", true, "server address");
		options.addOption("p", "port", true, "server port");
		options.addOption("l", "locationPrefix", true, "locatoin prefix");
		options.addOption("t", "threadId", true,
				"thread id on this slave machine");

		CommandLineParser parser = new PosixParser();
		CommandLine cmd = null;
		try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			log.fatal(e.getMessage());
			System.exit(1);
		}

		if (cmd.hasOption('h') || cmd.hasOption("help")) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("slave", options);
			System.exit(0);
		}

		String serverAddr = null;
		if (cmd.hasOption('s') || cmd.hasOption("server")) {
			serverAddr = cmd.getOptionValue('s');
		} else {
			log.fatal("server address missing!");
			System.exit(1);
		}

		String serverPort = null;
		if (cmd.hasOption('p') || cmd.hasOption("port")) {
			serverPort = cmd.getOptionValue('p');
		} else {
			log.fatal("server port missing!");
			System.exit(1);
		}

		String locationPrefix = null;
		if (cmd.hasOption('l') || cmd.hasOption("locationPrefix")) {
			locationPrefix = cmd.getOptionValue('l');
		} else {
			locationPrefix = "master";
		}

		URL url = null;
		try {
			url = new URL("http://" + serverAddr + ":" + serverPort + "/"
					+ locationPrefix + "/" + CommonStrings.REQUEST_SLAVE_TASK);
		} catch (MalformedURLException e) {
			log.fatal(" server address or port error or location prefix error! the url is "
					+ url);
			System.exit(1);
		}

		int threadId = 0;
		if (cmd.hasOption('t') || cmd.hasOption("threadId")) {
			threadId = Integer.parseInt(cmd.getOptionValue('t'));
		} else {
			log.fatal("thread id missing");
			System.exit(1);
		}

		cnf.setMasterHost(serverAddr);
		cnf.setMasterPort(serverPort);
		cnf.setLocationPrefix(locationPrefix);
		cnf.setThreadId(threadId);
		return cnf;
	}
}
